package com.halflife.framework.utils;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: ImageUploadUtil
 * @Description: 图片上传工具类，包括ckeditor操作
 */
public class ImageUploadUtil {

    // 图片类型
    private static List<String> fileTypes = new ArrayList<String>();

    static {
        fileTypes.add(".jpg");
        fileTypes.add(".jpeg");
        fileTypes.add(".bmp");
        fileTypes.add(".gif");
        fileTypes.add(".png");
        fileTypes.add(".svg");
    }

    /**
     * 图片上传
     *
     * @Title upload
     * @param request
     *            文件上传目录：比如upload(无需带前面的/) upload/news ..
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public static String upload(HttpServletRequest request, MultipartFile file) throws IllegalStateException,
            IOException {
        String fileName = null;
        //创建你要保存的文件的路径
        String path = request.getSession().getServletContext().getRealPath("");
        //获取该文件的文件名
        fileName = file.getOriginalFilename();
        //获取拓展名
        String ext = ImageUploadUtil.getExtention(fileName);
        fileName = RandomStringUtils.random(4, Num62.N36_CHARS) + ext;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        path = path + "fileUpload/" + sdf.format(new Date());
        File targetDir = new File(path);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        File targetFile = new File(path, fileName);
        file.transferTo(targetFile);
        return fileName;
    }
    public static String upload1(HttpServletRequest request, String base64String) throws Exception,
            IOException {
       //创建你要保存的文件的路径
        base64String = URLDecoder.decode(base64String);
        System.out.println(base64String);
        String path = request.getSession().getServletContext().getRealPath("");
        String fileName = RandomStringUtils.random(4, Num62.N36_CHARS) + ".svg";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        path = path + "fileUpload/" + sdf.format(new Date());
        File targetDir = new File(path);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        File targetFile = new File(path, fileName);
//        base64String = base64String.split(",")[1];//去掉base64码的data:image/png;base64,
//        System.out.println(base64String);
//        BASE64Decoder decoder = new BASE64Decoder();
//        // Base64解码
//        byte[] bytes = decoder.decodeBuffer(base64String);
//        for (int i = 0; i < bytes.length; ++i) {
//            if (bytes[i] < 0) {// 调整异常数据
//                bytes[i] += 256;
//            }
//        }
        Writer out = new FileWriter(targetFile);
        out.write(base64String);
        out.flush();
        out.close();
        return fileName;
    }

    /**
     * 日期格式化对象
     */
    public static final DateFormat MONTH_FORMAT = new SimpleDateFormat(
            "/yyyyMM/ddHHmmss");

    public static void checkDirAndCreate(File dir) {
        if (!dir.exists())
            dir.mkdirs();
    }

    public static String getExtention(String fileName){
        if(fileName!=null && fileName.length()>0 && fileName.lastIndexOf(".")>-1){
            return fileName.substring(fileName.lastIndexOf("."));
        }
        return "";
    }
}